﻿// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

    //Debug Variables
    var DEBUG = false;

    //Get strings out of resources
    var recentPostsTitle = WinJS.Resources.getString('recentPostsTitle').value;
    var categoryTitle = WinJS.Resources.getString('categoryTitle').value;
    var offlineTitle = WinJS.Resources.getString('offlineTitle').value;
    var aboutTitle = WinJS.Resources.getString('aboutTitle').value;
    var homeTitle = WinJS.Resources.getString('homeTitle').value;
    var sharingErrorMessage = WinJS.Resources.getString('shareErrorMessage').value;
    var appTitle = WinJS.Resources.getString('blogTitle').value;


    //Ad Variables
    var applicationId = WinJS.Resources.getString('applicationId').value;
    var adUnitId = WinJS.Resources.getString('adUnitId').value;

    var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
    var app = WinJS.Application;
    var appbarTileId;
    var currentCat = null;
    var promise = null;

    var appViewState = Windows.UI.ViewManagement.ApplicationViewState;

    var _options;
    var _element;
    var _viewState;
    //cache object
    //var cache = {};
    var cache = app.sessionState;
    var _items;

    var _loaded;

    //flyout items
    var _recent;
    var _home;
    var _offline;
    var _allCategories;
    var _saveItemForRemoval = [];
    var _saveAdsForRemoval = null;

    var _offlinePosts;
    var _cmdRemove;
    var _appbar;
    var _listview;

    var _contentIsLoaded = false;
    var _isOfflinePage = false;
    function log(str) {
      
        if (DEBUG && console && console.log) {
            console.log(str);
        }
    };

    WinJS.UI.Pages.define("/pages/groupDetail/groupDetail.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            _saveAdsForRemoval = [];
            _options = options;
            _element = element;
            _isOfflinePage = false;
            _listview = element.querySelector('#listView').winControl;
            _appbar = document.getElementById('appbar').winControl;

            var parent = element.querySelector('section');
            var pHeight = (parent.offsetHeight / 2) - parent.offsetTop;
            var ringContainer = element.querySelector('.progress-container');
            var rHeight = ringContainer.offsetHeight;
            var marginTop = pHeight + (rHeight / 2);
            ringContainer.style.marginTop = marginTop + "px";

            var backButton = element.querySelector(".win-backbutton");
            if (backButton.attributes[0].value == "disabled") {
                backButton.removeAttribute("disabled");
                //var backButton = element.querySelector(".win-backbutton");
                backButton.addEventListener('click', backButtonHandler, false);
            }

            //Share fail dialog
            dataTransferManager.addEventListener("datarequested", dataRequested);


            this._initializeLayout(Windows.UI.ViewManagement.ApplicationView.value, element, options);


        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
            _items = null;
            if (promise != null) {
                promise.cancel();
            }

            _recent.removeEventListener("click", flyoutRecentItemHandler);
            _home.removeEventListener("click", flyoutHomeItemHandler);
            if (typeof _offline !== "undefined") {
                _offline.removeEventListener("click", flyoutOfflineItemHandler);
            }
            _allCategories.removeEventListener("click", flyoutAllCategoriesItemHandler);
            for (var i = 0; i < _saveItemForRemoval.length; i++) {
                _saveItemForRemoval[i].removeEventListener("click", flyoutUnkownItemHandler);
            }

            for (var i = 0; i < _saveAdsForRemoval.length; i++) {
                _saveAdsForRemoval[i].dispose(true);
            }
            _saveAdsForRemoval = null;

            var backButton = _element.querySelector(".win-backbutton");
            backButton.removeEventListener('click', backButtonHandler);

            _element.querySelector("#commandButton").removeEventListener("click", appbarButtonClicked);
            if (typeof _cmdRemove !== "undefined") {
                _cmdRemove.removeEventListener("click", cmdRemoveHandler);
            }
            _element.querySelector("#groupHeaderTag").removeEventListener('click', showHeaderMenu);

            _appbar.removeEventListener("afterhide", afterhideHandler);

            _listview.removeEventListener('contextmenu', contextmenuHandler);



            //Share fail dialog
            dataTransferManager.removeEventListener("datarequested", dataRequested);
        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />
            if (promise != null) {
                promise.cancel();
            }

            _viewState = viewState;

            _listview.removeEventListener("selectionchanged");
            _listview.removeEventListener("contextmenu");

            if (lastViewState !== viewState) {
                if (lastViewState === appViewState.snapped || viewState === appViewState.snapped) {

                    this._initializeLayout(viewState, element, _options);
                }
            } else {
                this._initializeLayout(viewState, element, _options);
            }
        },

        getAnimationElements: function () {
            return [[this.element.querySelector("header")], [this.element.querySelector("section")]];
        },

        _initializeLayout: function (viewState, element, options) {

            toggleLoading(true);

            initHeaderMenu(element, _options);

            _appbar.sticky = true;
            _appbar.disabled = false;

            //hide commands
            _appbar.hideCommands('commandButton', false);
            _appbar.hideCommands('cmdRemove', false);


            _appbar.addEventListener("afterhide", afterhideHandler, false);

            _listview.selectionMode = 'none';
            _listview.addEventListener('contextmenu', contextmenuHandler, false);
            _listview.addEventListener("selectionchanged", selectionchangedHandler, false);
            if (options.from === 'headerButton') {

                var headerTitle = options.headerTitle;

                element.querySelector('#groupHeaderTitle').innerHTML = headerTitle;

                if (headerTitle === recentPostsTitle) {
                    _appbar.disabled = true;

                    if (typeof cache[recentPostsTitle] === "undefined") {
                        promise = Data.getRecentPosts(10, true).then(function (posts) {
                            _items = posts;
                            if (promise._state.name == "canceled") {
                                return;
                            }
                            if (posts === null || typeof posts === "undefined") {
                                log("no items, maybe offline");
                                var errorDiv = element.querySelector("#errorDiv");
                                element.querySelector("#errorDiv").style.display = "block";
                                errorDiv.innerText = "Im Moment besteht keine Internetverbindung.";
                            } else {
                                var errorDiv = _element.querySelector("#errorDiv");
                                if (errorDiv !== null){
                                    errorDiv.style.display = "none";
                                }
                                //save data
                                cache[recentPostsTitle] = posts;

                                if (viewState === appViewState.snapped) {
                                    var noAd = posts.filter(function (post) {
                                        if (typeof post.ad != "undefined") {
                                            return 0;
                                        } else {
                                            return 1;
                                        }
                                    });

                                    _listview.oniteminvoked = function (e) {
                                        log('postitemInvoked');
                                        WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: noAd[e.detail.itemIndex] });
                                    };

                                    var list = new WinJS.Binding.List(noAd);
                                    _listview.layout = new WinJS.UI.ListLayout();
                                    WinJS.UI.setOptions(_listview, {
                                        itemDataSource: list.dataSource,
                                        itemTemplate: itemTemplateFunctionSnap
                                    });

                                } else {
                                    var list = new WinJS.Binding.List(posts);

                                    var gridLayoutOptions = {
                                        groupHeaderPosition: 'top',
                                        groupInfo: { enableCellSpanning: true, cellWidth: 250, cellHeight: 55 }
                                    };

                                    _listview.oniteminvoked = function (e) {
                                        log('postitemInvoked');
                                        if (posts[e.detail.itemIndex].ad !== true) {
                                            WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: posts[e.detail.itemIndex] });
                                        }
                                    };

                                    _listview.layout = new WinJS.UI.GridLayout(gridLayoutOptions);
                                    WinJS.UI.setOptions(_listview, {
                                        itemDataSource: list.dataSource,
                                        itemTemplate: itemTemplateFunction
                                    });
                                }

                            }
                            toggleLoading(false);

                        });
                    } else {
                        //load cached data
                        var posts = cache[recentPostsTitle];

                        if (viewState === appViewState.snapped) {
                            var noAd = posts.filter(function (post) {
                                if (typeof post.ad != "undefined") {
                                    return 0;
                                } else {
                                    return 1;
                                }
                            });

                            _listview.oniteminvoked = function (e) {
                                log('postitemInvoked');
                                WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: noAd[e.detail.itemIndex] });
                            };

                            var list = new WinJS.Binding.List(noAd);
                            _listview.layout = new WinJS.UI.ListLayout();
                            WinJS.UI.setOptions(_listview, {
                                itemDataSource: list.dataSource,
                                itemTemplate: itemTemplateFunctionSnap
                            });

                        } else {
                            _listview.oniteminvoked = function (e) {
                                log('postitemInvoked');
                                if (posts[e.detail.itemIndex].ad !== true) {
                                    WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: posts[e.detail.itemIndex] });
                                }
                            };

                            var list = new WinJS.Binding.List(posts);

                            var gridLayoutOptions = {
                                groupHeaderPosition: 'top',
                                groupInfo: { enableCellSpanning: true, cellWidth: 250, cellHeight: 55 }
                            };
                            _listview.layout = new WinJS.UI.GridLayout(gridLayoutOptions);
                            WinJS.UI.setOptions(_listview, {
                                itemDataSource: list.dataSource,
                                itemTemplate: itemTemplateFunction
                            });
                        }
                        toggleLoading(false);
                    }

                } else if (headerTitle === categoryTitle) {
                    _appbar.disabled = true;
                    if (typeof cache[categoryTitle] === "undefined") {
                        _appbar.disabled = true;
                        //load data
                        promise = Data.getAllRecentPosts(null, true).then(function (posts) {
                            _items = posts;
                            if (promise._state.name == "canceled") {
                                return;
                            }
                            if (posts === null || typeof posts === "undefined") {

                                log("no items, maybe offline");
                                var errorDiv = element.querySelector("#errorDiv");
                                element.querySelector("#errorDiv").style.display = "block";
                                errorDiv.innerText = "Im Moment besteht keine Internetverbindung.";
                            } else {
                                element.querySelector("#errorDiv").style.display = "none";
                                //save data
                                cache[categoryTitle] = posts;

                                _listview.oniteminvoked = function (e) {
                                    log('postitemInvoked');
                                    if (posts[e.detail.itemIndex].ad !== true) {
                                        WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: posts[e.detail.itemIndex] });
                                    }
                                };

                                if (viewState === appViewState.snapped) {
                                    var noAd = posts.filter(function (post) {
                                        if (typeof post.ad != "undefined") {
                                            return 0;
                                        } else {
                                            return 1;
                                        }
                                    });
                                    var list = new WinJS.Binding.List(noAd);
                                    _listview.layout = new WinJS.UI.ListLayout();
                                    WinJS.UI.setOptions(_listview, {
                                        itemDataSource: list.dataSource,
                                        itemTemplate: itemTemplateFunctionSnap
                                    });

                                } else {
                                    var list = new WinJS.Binding.List(posts);

                                    var gridLayoutOptions = {
                                        groupHeaderPosition: 'top',
                                        groupInfo: { enableCellSpanning: true, cellWidth: 250, cellHeight: 55 }
                                    };
                                    _listview.layout = new WinJS.UI.GridLayout(gridLayoutOptions);
                                    WinJS.UI.setOptions(_listview, {
                                        itemDataSource: list.dataSource,
                                        itemTemplate: itemTemplateFunction
                                    });
                                }

                            }

                            toggleLoading(false);

                        });
                    } else {

                        //load cached data
                        
                        var posts = cache[categoryTitle];

                        if (viewState === appViewState.snapped) {
                            var noAd = posts.filter(function (post) {
                                if (typeof post.ad != "undefined") {
                                    return 0;
                                } else {
                                    return 1;
                                }
                            });

                            _listview.oniteminvoked = function (e) {
                                log('postitemInvoked');
                                WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: noAd[e.detail.itemIndex] });
                            };

                            var list = new WinJS.Binding.List(noAd);
                            _listview.layout = new WinJS.UI.ListLayout();
                            WinJS.UI.setOptions(_listview, {
                                itemDataSource: list.dataSource,
                                itemTemplate: itemTemplateFunctionSnap
                            });

                        } else {
                            _listview.oniteminvoked = function (e) {
                                log('postitemInvoked');
                                if (posts[e.detail.itemIndex].ad !== true) {
                                    WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: posts[e.detail.itemIndex] });
                                }
                            };

                            var list = new WinJS.Binding.List(posts);

                            var gridLayoutOptions = {
                                groupHeaderPosition: 'top',
                                groupInfo: { enableCellSpanning: true, cellWidth: 250, cellHeight: 55 }
                            };
                            _listview.layout = new WinJS.UI.GridLayout(gridLayoutOptions);
                            WinJS.UI.setOptions(_listview, {
                                itemDataSource: list.dataSource,
                                itemTemplate: itemTemplateFunction
                            });
                        }
                        toggleLoading(false);
                    }

                } else if (headerTitle === offlineTitle) {

                    _appbar.disabled = true;
                    _isOfflinePage = true;
                    //#_listview.addEventListener("selectionchanged", selectionchangedHandler, false);

                    promise = Data.loadData(null, true).then(function (offlinePosts) {
                        _items = offlinePosts;

                        _offlinePosts = offlinePosts;
                        _listview.selectionMode = 'multi';
                        _appbar.showCommands('cmdRemove', false);
                        _cmdRemove = document.getElementById("cmdRemove");
                        _cmdRemove.addEventListener("click", cmdRemoveHandler, false);

                        function postItemInvoked(e) {
                            log('postitemInvoked');
                            WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: _offlinePosts[e.detail.itemIndex] });
                        }

                        _listview.oniteminvoked = postItemInvoked;

                        if (viewState === appViewState.snapped) {
                            var noAd = _offlinePosts.filter(function (post) {
                                if (typeof post.ad != "undefined") {
                                    return 0;
                                } else {
                                    return 1;
                                }
                            });
                            var list = new WinJS.Binding.List(noAd);
                            _listview.layout = new WinJS.UI.ListLayout();
                            WinJS.UI.setOptions(_listview, {
                                itemDataSource: list.dataSource,
                                itemTemplate: itemTemplateFunctionSnap
                            });

                        } else {
                            var list = new WinJS.Binding.List(_offlinePosts);

                            var gridLayoutOptions = {
                                groupHeaderPosition: 'top',
                                groupInfo: { enableCellSpanning: true, cellWidth: 250, cellHeight: 55 }
                            };
                            _listview.layout = new WinJS.UI.GridLayout(gridLayoutOptions);
                            WinJS.UI.setOptions(_listview, {
                                itemDataSource: list.dataSource,
                                itemTemplate: itemTemplateFunction
                            });
                        }
                        toggleLoading(false);
                    });
                }
            } else if (options.from === 'categoryItem') {
                if (options.item == null) {
                    var catTitle = options.headerTitle;
                } else {
                    var catTitle = options.item.title;
                }


                _appbar.showCommands('commandButton', false);

                element.querySelector('#groupHeaderTitle').innerHTML = catTitle;
                
                if (options.item == null) {
                    _appbar.disabled = true;
                } else {
                    _appbar.disabled = false;
                    _appbar.sticky = true;
                    appbarTileId = "SecondaryTile." + options.item.id;
                }
                currentCat = options.item;
                setAppbarButton(appbarTileId);
                _element.querySelector("#commandButton").addEventListener("click", appbarButtonClicked, false);

                if (typeof cache[catTitle] === "undefined") {
                    //load new data
                    if (options.item == null) {
                        var errorDiv = element.querySelector("#errorDiv");
                        element.querySelector("#errorDiv").style.display = "block";
                        errorDiv.innerText = "Im Moment besteht keine Internetverbindung.";
                        toggleLoading(false);

                        return;
                    } else {
                        element.querySelector("#errorDiv").style.display = "none";
                    }
                    promise = Data.getPostsByCategorySlug(options.item, null, true).then(function (posts) {
                        _items = posts;

                        if (promise._state.name == "canceled") {
                            return;
                        }
                        if (posts === null || typeof posts === "undefined") {
                            log("no items, maybe offline");
                            var errorDiv = element.querySelector("#errorDiv");
                            element.querySelector("#errorDiv").style.display = "block";
                            errorDiv.innerText = "Im Moment besteht keine Internetverbindung.";
                        } else {
                            if (typeof element.querySelector("#errorDiv").style !== "undefined") {                             
                                element.querySelector("#errorDiv").style.display = "none";
                            }
                            //save data
                            cache[catTitle] = posts;


                            if (viewState === appViewState.snapped) {
                                var noAd = posts.filter(function (post) {
                                    if (typeof post.ad != "undefined") {
                                        return 0;
                                    } else {
                                        return 1;
                                    }
                                });
                                var list = new WinJS.Binding.List(noAd);
                                _listview.layout = new WinJS.UI.ListLayout();

                                _listview.oniteminvoked = function (e) {
                                    log('singleCategoryItemInvoked');
                                    WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: noAd[e.detail.itemIndex] });
                                };

                                WinJS.UI.setOptions(_listview, {
                                    itemDataSource: list.dataSource,
                                    itemTemplate: itemTemplateFunctionSnap
                                });

                            } else {
                                var list = new WinJS.Binding.List(posts);

                                var gridLayoutOptions = {
                                    groupHeaderPosition: 'top',
                                    groupInfo: { enableCellSpanning: true, cellWidth: 250, cellHeight: 55 }
                                };
                                _listview.layout = new WinJS.UI.GridLayout(gridLayoutOptions);

                                _listview.oniteminvoked = function (e) {
                                    log('singleCategoryItemInvoked');
                                    if (posts[e.detail.itemIndex].ad !== true) {
                                        WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: posts[e.detail.itemIndex] });
                                    }
                                };

                                WinJS.UI.setOptions(_listview, {
                                    itemDataSource: list.dataSource,
                                    itemTemplate: itemTemplateFunction
                                });
                            }
                        }
                        toggleLoading(false);

                    });
                } else {
                    //load cached data

                    var posts = cache[catTitle];


                    if (viewState === appViewState.snapped) {
                        var noAd = posts.filter(function (post) {
                            if (typeof post.ad != "undefined") {
                                return 0;
                            } else {
                                return 1;
                            }
                        });
                        var list = new WinJS.Binding.List(noAd);
                        _listview.layout = new WinJS.UI.ListLayout();

                        _listview.oniteminvoked = function (e) {
                            log('singleCategoryItemInvoked');
                            WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: noAd[e.detail.itemIndex] });
                        };

                        WinJS.UI.setOptions(_listview, {
                            itemDataSource: list.dataSource,
                            itemTemplate: itemTemplateFunctionSnap
                        });

                    } else {
                        var list = new WinJS.Binding.List(posts);

                        var gridLayoutOptions = {
                            groupHeaderPosition: 'top',
                            groupInfo: { enableCellSpanning: true, cellWidth: 250, cellHeight: 55 }
                        };
                        _listview.layout = new WinJS.UI.GridLayout(gridLayoutOptions);

                        _listview.oniteminvoked = function (e) {
                            log('singleCategoryItemInvoked');
                            if (posts[e.detail.itemIndex].ad !== true) {
                                WinJS.Navigation.navigate('/pages/itemDetail/itemDetail.html', { item: posts[e.detail.itemIndex] });
                            }
                        };

                        WinJS.UI.setOptions(_listview, {
                            itemDataSource: list.dataSource,
                            itemTemplate: itemTemplateFunction
                        });
                    }
                    toggleLoading(false);

                }
            }

        }

    });

    function toggleLoading(isLoading) {
        if (isLoading) {
            _element.querySelector(".progress-container").style.display = "block";
            _element.querySelector('#fullContainer').style.display = "none";


            _contentIsLoaded = false;
        }
        else {
            _element.querySelector(".progress-container").style.display = "none";
            _element.querySelector('#fullContainer').style.display = "block";
            _contentIsLoaded = true;
        }
    }

    function afterhideHandler(parameters) {
        var list = _element.querySelector('#listView');
        list.winControl.selection.clear();
    }
    function contextmenuHandler(parameters) {
        if (_isOfflinePage) {
            if (_listview != null) {
                if (typeof _listview.selection !== "undefined") {
                    log(_listview.selection.count());
                    if (_listview.selection.count() === 1) {
                        _appbar.show();
                    }
                }
            }
        }

    }
    function selectionchangedHandler(e) {
        if (_isOfflinePage) {
            if (_listview.selection.count() > 0) {
                var x = _listview.selection.count();
                _appbar.disabled = false;
                _appbar.show();
            } else {
                _appbar.hide();
                _appbar.disabled = true;
            }
        }

    }
    function backButtonHandler(parameters) {
        if (promise != null) {
            promise.cancel();
        }
        WinJS.Navigation.navigate('/pages/home/home.html');
    }

    //function for secondary tile
    function setAppbarButton() {
        
        var cmdBTN = document.getElementById("commandButton");

        if (Windows.UI.StartScreen.SecondaryTile.exists(appbarTileId)) {
            if (typeof cmdBTN !== "undefined") {
                cmdBTN.winControl.label = "Vom Startmenü lösen";
                cmdBTN.winControl.icon = WinJS.UI.AppBarIcon.unpin;
                cmdBTN.winControl.tooltip = "Vom Startmenü lösen";
            }

        } else {
            if (typeof cmdBTN !== "undefined") {
                cmdBTN.winControl.label = "An Startmenü anheften";
                cmdBTN.winControl.icon = WinJS.UI.AppBarIcon.pin;
                cmdBTN.winControl.tooltip = "An Startmenü anheften";
            }
        }
    }

    function appbarButtonClicked() {

        if (WinJS.UI.AppBarIcon.unpin === document.getElementById("commandButton").winControl.icon) {
            unpinByElementAsync(document.getElementById("commandButton"), appbarTileId).done(function (isDeleted) {
                if (isDeleted) {
                    WinJS.log && WinJS.log("Secondary tile was successfully unpinned.", "sample", "status");
                    setAppbarButton();
                } else {
                    WinJS.log && WinJS.log("Secondary tile was not unpinned.", "sample", "error");
                    setAppbarButton();
                }
            });
        } else {
            pinByElementAsync(document.getElementById("commandButton"), appbarTileId, "App bar pinned secondary tile", "A secondary tile that was pinned by the user from the app bar").done(function (isCreated) {
                if (isCreated) {
                    WinJS.log && WinJS.log("Secondary tile was successfully pinned.", "sample", "status");
                    setAppbarButton();
                } else {
                    WinJS.log && WinJS.log("Secondary tile was not pinned.", "sample", "error");
                    setAppbarButton();
                }
            });
        }
    }

    function pinByElementAsync(element, newTileID, newTileShortName, newTileDisplayName) {
        var uriLogo = new Windows.Foundation.Uri("ms-appx:///images/assets/smallLogo_30x30.png");
        var uriWideLogo = new Windows.Foundation.Uri("ms-appx:///images/assets/wideLogo_310x150.png");
        var uriSmallLogo = new Windows.Foundation.Uri("ms-appx:///images/assets/logo_150x150.png");

        var catName = Helper.htmlSpecialChars(currentCat.title, true);
        var catObject = JSON.stringify(currentCat);
        var tileActivationArguments = catObject;

        var tile = new Windows.UI.StartScreen.SecondaryTile(newTileID,
                                                            appTitle + " - " + catName,
                                                            "Secondary Tile of " + appTitle,
                                                            tileActivationArguments,
                                                            2,
                                                            uriSmallLogo,
                                                            uriWideLogo);

        tile.foregroundText = Windows.UI.StartScreen.ForegroundText.dark;
        tile.smallLogo = uriLogo;

        var selectionRect = element.getBoundingClientRect();
        var buttonCoordinates = { x: selectionRect.left, y: selectionRect.top, width: selectionRect.width, height: selectionRect.height };
        var placement = Windows.UI.Popups.Placement.above;

        return new WinJS.Promise(function (complete, error, progress) {
            tile.requestCreateForSelectionAsync(buttonCoordinates, placement).done(function (isCreated) {
                if (isCreated) {
                    complete(true);
                    //call update method
                    TileUpdate.updateTile();
                } else {
                    complete(false);
                }
            });
        });
    }

    function unpinByElementAsync(element, unwantedTileID) {

        var selectionRect = element.getBoundingClientRect();
        var buttonCoordinates = { x: selectionRect.left, y: selectionRect.top, width: selectionRect.width, height: selectionRect.height };
        var placement = Windows.UI.Popups.Placement.above;

        var tileToDelete = new Windows.UI.StartScreen.SecondaryTile(unwantedTileID);

        return new WinJS.Promise(function (complete, error, progress) {
            tileToDelete.requestDeleteForSelectionAsync(buttonCoordinates, placement).done(function (isDeleted) {
                if (isDeleted) {
                    complete(true);
                } else {
                    complete(false);
                }
            });
        });
    }

    function initHeaderMenu(element, options) {

        _loaded = false;

        var currentTitle = '';
        if (_options.from === 'headerButton') {
            currentTitle = _options.headerTitle;
        } else if (_options.from === 'categoryItem') {
            if (_options.item == null) {
                currentTitle = _options.headerTitle;
            } else {
                currentTitle = _options.item.title;
            }

        }

        var menu = document.getElementById("headerMenu");
        var menuControl = menu.winControl;

        element.querySelector("#groupHeaderContainer").addEventListener('click', showHeaderMenu, false);

        var commands = [];

        _recent = new WinJS.UI.MenuCommand(null, { id: 'recentMenuItem', label: recentPostsTitle });
        _recent.addEventListener("click", flyoutRecentItemHandler, false);
        commands.push(_recent);

        var seperator = new WinJS.UI.MenuCommand(null, { id: 'seperatorMenuItem', type: 'seperator' });

        _home = new WinJS.UI.MenuCommand(null, { id: 'homeMenuItem', label: homeTitle });
        _home.addEventListener("click", flyoutHomeItemHandler, false);

        //offline menu item
        promise = Data.loadData(null, true).then(function (c) {
            if (c.length !== 0) {
                if (c.length > 0) {
                    
                    _offline = new WinJS.UI.MenuCommand(null, { id: 'offlineMenuItem', label: offlineTitle });
                    _offline.addEventListener("click", flyoutOfflineItemHandler, false);
                    commands.push(_offline);


                }
            }
        }).then(function (parameters) {

            _allCategories = new WinJS.UI.MenuCommand(null, { id: 'allCategoriesMenuItem', label: categoryTitle });
            _allCategories.addEventListener("click", flyoutAllCategoriesItemHandler, false);
            commands.push(_allCategories);

            if (typeof cache["getCategories"] !== "undefined") {

                //load cached data
                var list = cache["getCategories"];
                if (list != null) {
                    for (var i = 0; i < list.length; i++) {
                        var escapedTitle = Helper.htmlSpecialChars(list[i].title, true);
                        var command = new WinJS.UI.MenuCommand(null, { id: list[i].title, label: escapedTitle });
                        command.addEventListener('click', flyoutUnkownItemHandler, false);
                        _saveItemForRemoval.push(command);
                        commands.push(command);
                    }
                }

                commands.push(seperator);
                commands.push(_home);
                menuControl.commands = commands;

                checkActiveMenuItem(menuControl, currentTitle, commands);

                _loaded = true;
            } else {

                //load data
                promise = Data.getCategories().then(function (list) {
                    if (list != null) {
                        cache["getCategories"] = list;
                        for (var i = 0; i < list.length; i++) {
                            var escapedTitle = Helper.htmlSpecialChars(list[i].title, true);
                            var command = new WinJS.UI.MenuCommand(null, { id: list[i].title, label: escapedTitle });
                            command.addEventListener('click', flyoutUnkownItemHandler, false);
                            _saveItemForRemoval.push(command);
                            commands.push(command);
                        }
                    }

                    commands.push(seperator);
                    commands.push(_home);
                    menuControl.commands = commands;

                    checkActiveMenuItem(menuControl, currentTitle, commands);

                    _loaded = true;
                });
            }

        });

    };

    function showHeaderMenu() {
        var title = _element.querySelector('#groupHeaderTag');
        var menu = document.getElementById("headerMenu").winControl;
        menu.anchor = title;
        menu.placement = "bottom";
        menu.alignment = "left";
        if (_loaded && _contentIsLoaded) {
            menu.show();
        }
    }

    function checkActiveMenuItem(menu, title, commands) {
        for (var i = 0; i < commands.length; i++) {
            if (commands[i].label == title) {
                commands[i].element.innerHTML = "<div class='activeMenuItem'>" + title + "</div>";
            }
            if (commands[i].id == "seperatorMenuItem") {
                commands[i].element.innerHTML = "<div class='menuSeperator'></div>";
            }
        }
    }

    function cmdRemoveHandler() {

        log("remove button offlinePosts pressed");

        var selected = _listview.selection;
        var count = selected.count();
        log("Remove button pressed " + count);
        var is = selected.getItems();
        if (typeof count === "undefined" || count == 0) {
            return;
        }
        var listOfPostIds = [];
        for (var i = 0; i < is._value.length; i++) {
            var p = _offlinePosts[is._value[i].index];
            log(p.title);
            //savePromises.push(Data.saveToOfflineList(p));

            listOfPostIds.push(p.id);
        }

        //delete post by id
        Data.deletePosts(listOfPostIds);

        //UI delete

        var ds = _listview.itemDataSource;
        if (_listview.selection.count() > 0) {
            _listview.selection.getItems().done(function (items) {

                // Start a batch for the edits
                ds.beginEdits();

                // To remove the items, call remove on the itemDataSource passing in the key
                items.forEach(function (currentItem) {
                    ds.remove(currentItem.key);
                });

                // End the batch of edits
                ds.endEdits();
            });
        }
        //hide appbar
        _appbar.hide();

    }

    function flyoutRecentItemHandler() {
        WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
            from: 'headerButton',
            headerTitle: recentPostsTitle
        });
    }
    function flyoutHomeItemHandler() {
        WinJS.Navigation.navigate('/pages/home/home.html');
    }
    function flyoutOfflineItemHandler() {
        WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
            from: 'headerButton',
            headerTitle: offlineTitle
        });
    }
    function flyoutAllCategoriesItemHandler() {
        WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
            from: 'headerButton',
            headerTitle: categoryTitle
        });
    }
    function flyoutUnkownItemHandler(e) {

        WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
            from: 'categoryItem',
            item: getCatByID(e.srcElement.id),
            headerTitle: e.srcElement.innerText
        });

    }

    // Template Function
    function itemTemplateFunction(itemPromise) {
        return itemPromise.then(function (item) {

            // Select template
            var itemTemplate = document.getElementById("itemTemplate-RecentPost");
            if (typeof item.data.ad !== "undefined") {
                var adDiv = document.createElement("div");
                adDiv.style.height = "250px";
                adDiv.style.width = "250px";
                var myAdControl = new MicrosoftNSJS.Advertising.AdControl(adDiv,
                                {
                                    applicationId: applicationId,
                                    adUnitId: adUnitId
                                });
                _saveAdsForRemoval.push(myAdControl);

                return adDiv;
            } else {
                if (item.data.teaserImage !== undefined) {
                    if (item.data.teaserImage == false) {
                        itemTemplate = _element.querySelector('#itemTemplate-RecentPost');
                    } else {
                        itemTemplate = _element.querySelector('#itemTemplate-Image');
                       
                    }
                } else {
                    itemTemplate = _element.querySelector('#itemTemplate-RecentPost');
                }
            }

            // Render selected template to DIV container
            var container = document.createElement("div");
            if (itemTemplate !== null) {
                itemTemplate.winControl.render(item.data, container);
                return container;
            }

        });
    }

    function itemTemplateFunctionSnap(itemPromise) {
        return itemPromise.then(function (item) {

            // Select template
            var itemTemplate = document.getElementById("snapItem");
            if (item.data.teaserImage !== undefined) {
                if (item.data.teaserImage == false) {
                    itemTemplate = _element.querySelector('#snapItem');
                } else {
                    itemTemplate = _element.querySelector('#snapItem-image');
                }
            } else {
                itemTemplate = _element.querySelector('#snapItem');
            }
            // Render selected template to DIV container
            var container = document.createElement("div");
            if (itemTemplate !== null) {
                itemTemplate.winControl.render(item.data, container);
                return container;
            }

        });
    }

    function dataRequested(e) {
        var request = e.request;
        if (sharingErrorMessage) {
            request.failWithDisplayText(sharingErrorMessage);
        } else {
            request.failWithDisplayText("Derzeit sind keine Inhalte zum Teilen vorhanden.");
        };
    }

    function getCatByID(id) {
        if (typeof cache["getCategories"] !== "undefined") {
            var cats = cache["getCategories"];
            for (var i = 0; i < cats.length; i++) {
                if (cats[i].title == id) {
                    return cats[i];
                }
            }
            return null;
        } else {
            return null;
        }
    }

})();
